import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

# ---------------- 全局配置 ----------------
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Times New Roman"]
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams.update({
    "font.size": 12,
    "axes.labelsize": 14,
    "axes.titlesize": 16,
    "legend.fontsize": 11,
    "grid.linestyle": "--",
    "grid.alpha": 0.7
})

# 尝试开启 LaTeX，失败时自动关闭
try:
    plt.rcParams["text.usetex"] = True
    plt.rcParams["text.latex.preamble"] = [
        r"\usepackage{amsmath}",
        r"\usepackage{amsfonts}",
        r"\usepackage{amsbsy}"
    ]
except Exception:
    plt.rcParams["text.usetex"] = False


def plot_effective_shielding_interval():
    """绘制有效遮蔽时间积分区间示意图 + 甘特图"""

    # ---------------- 参数设置 ----------------
    t_total = 70
    t = np.linspace(0, t_total, 1000)

    # 各状态时间区间
    smoke_effective_start, smoke_effective_end = 22, 55
    smoke_ground_start, smoke_ground_end = 20, 50
    missile_detect_start, missile_detect_end = 25, 60

    smoke_effective = np.where((t >= smoke_effective_start) & (t <= smoke_effective_end), 1, 0)
    smoke_not_ground = np.where((t >= smoke_ground_start) & (t <= smoke_ground_end), 1, 0)
    missile_detect = np.where((t >= missile_detect_start) & (t <= missile_detect_end), 1, 0)

    effective_interval = smoke_effective * smoke_not_ground * missile_detect

    # 积分区间边界
    t_start = max(smoke_effective_start, smoke_ground_start, missile_detect_start)
    t_end = min(smoke_effective_end, smoke_ground_end, missile_detect_end)
    delta_t = t_end - t_start

    # ---------------- 绘图 ----------------
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), gridspec_kw={'height_ratios': [2, 1]})

    # ---- (上) 状态曲线图 ----
    ax1.plot(t, smoke_effective, "g-", linewidth=2.2, label="烟幕自身有效")
    ax1.plot(t, smoke_not_ground, "y--", linewidth=2.2, label="烟幕未触地")
    ax1.plot(t, missile_detect, "b-.", linewidth=2.2, label="导弹能探测真目标")

    ax1.add_patch(Rectangle((t_start, 0), delta_t, 1.05,
                            color="black", alpha=0.25, zorder=1,
                            label=fr"有效遮蔽区间 $[{t_start}, {t_end}]$s"))

    ax1.axvline(x=t_start, color="red", linestyle="--", linewidth=1.5)
    ax1.axvline(x=t_end, color="red", linestyle="--", linewidth=1.5)

    ax1.text(t_start, 1.12, fr"$t_{{start}}={t_start}$s", color="red",
             fontsize=12, fontweight="bold", ha="center")
    ax1.text(t_end, 1.12, fr"$t_{{end}}={t_end}$s", color="red",
             fontsize=12, fontweight="bold", ha="center")

    ax1.annotate(fr"$\Delta t = {delta_t}$s",
                 xy=((t_start + t_end) / 2, 1.05),
                 xytext=(0, 25), textcoords="offset points",
                 arrowprops=dict(arrowstyle="<->", color="red", lw=1.5),
                 ha="center", color="red", fontsize=12, weight="bold")

    ax1.set_xlim(0, t_total)
    ax1.set_ylim(-0.1, 1.25)
    ax1.set_xlabel("时间 (s)")
    ax1.set_ylabel("有效状态")
    ax1.set_yticks([0, 1])
    ax1.set_yticklabels(["无效", "有效"])
    ax1.set_title("有效遮蔽时间积分区间界定示意图", fontsize=18, pad=20)
    ax1.legend(loc="upper right", frameon=True, framealpha=0.9, edgecolor="gray")
    ax1.grid(True, axis="x")

    # ---- (下) 甘特图 ----
    intervals = [
        ("烟幕自身有效", smoke_effective_start, smoke_effective_end, "green"),
        ("烟幕未触地", smoke_ground_start, smoke_ground_end, "gold"),
        ("导弹能探测真目标", missile_detect_start, missile_detect_end, "dodgerblue"),
    ]

    for i, (label, start, end, color) in enumerate(intervals, start=1):
        ax2.broken_barh([(start, end - start)], (i - 0.4, 0.8), facecolors=color, alpha=0.7)
        ax2.text(start - 1, i, label, va="center", ha="right", fontsize=12)

    # 高亮有效遮蔽区间
    ax2.broken_barh([(t_start, delta_t)], (0.2, 0.6), facecolors="black", alpha=0.5)
    ax2.text((t_start + t_end) / 2, 0.5, fr"有效区间 $\Delta t={delta_t}$s",
             color="white", fontsize=12, ha="center", va="center", weight="bold")

    ax2.set_xlim(0, t_total)
    ax2.set_ylim(-0.5, 3.5)
    ax2.set_xlabel("时间 (s)")
    ax2.set_yticks([])
    ax2.set_title("时间轴表示（甘特图风格）", fontsize=16, pad=10)
    ax2.grid(True, axis="x", linestyle="--", alpha=0.6)

    # ---- 图注 ----
    plt.figtext(0.5, 0.01,
                (fr"$t_{{start}}=\max({smoke_effective_start}, {smoke_ground_start}, {missile_detect_start})={t_start}$s,  "
                 fr"$t_{{end}}=\min({smoke_effective_end}, {smoke_ground_end}, {missile_detect_end})={t_end}$s. "
                 "阴影/黑条区域为积分区间。"),
                ha="center", fontsize=12,
                bbox=dict(facecolor="white", alpha=0.8, boxstyle="round,pad=0.5"))

    plt.tight_layout()
    plt.savefig("effective_shielding_interval_with_gantt.png", dpi=300, bbox_inches="tight")
    plt.show()


if __name__ == "__main__":
    plot_effective_shielding_interval()
